package com.ruoyi.flowable.utils;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.flowable.domain.vo.AppVo;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
public class FlowableUtils {

    @Resource
    private RepositoryService repositoryService;

    @Resource
    protected RuntimeService runtimeService;

    //部署流程图
    public Deployment deploy(AppVo app, String xml) throws IOException {
        try (InputStream in = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))) {
            return repositoryService.createDeployment()
                .addInputStream(app.getAppName() + ".bpmn", in)
                .name(app.getAppName())
                .key(app.getAppId().toString())
                .deploy();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    //通过部署id查询定义
    public ProcessDefinition getDefinByDeployId(String deploymentId){
        return repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
    }

    public ProcessDefinition getDefinById(String defId){
        return repositoryService.createProcessDefinitionQuery().processDefinitionId(defId).singleResult();
    }


    public ProcessInstance startInst(String defId, Map<String, Object> variables){
        return runtimeService.createProcessInstanceBuilder().processDefinitionId(defId).variables(variables)
//                .name(processDefinition.getName())
            .start();
    }
}
